package com.example.interesting.distributed.log.realize.resttemplate;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 全局restTemplate过滤器添加
 * @Author: fyw
 * @Date: 2024/4/5 16:13
 * @History
 */
public class LogRestTemplatePostProcessor implements BeanPostProcessor, PriorityOrdered {


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RestTemplateBuilder) {
            RestTemplate restTemplate = ((RestTemplateBuilder) bean).build();
            restTemplate.setInterceptors(interceptors());
        }
        if (bean instanceof RestTemplate) {
            ((RestTemplate) bean).setInterceptors(interceptors());
        }
        return bean;
    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }

    private List<ClientHttpRequestInterceptor> interceptors() {
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new LogRestTemplateInterceptor());
        return interceptors;
    }
}
